package com.kordar.auth;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class AuthFilter extends AuthorizationFilter {

    AuthService authService;

    public void setAuthService(AuthService authService) {
        this.authService = authService;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) {

        Subject subject = SecurityUtils.getSubject();
        String principal = (String) subject.getPrincipal();


        // 获取主体为null
        if (principal == null) {
            return false;
        }

        // 检查用户是否有效
        Admin admin = authService.findOneByUsername((String) subject.getPrincipal());
        if (admin == null) {
            subject.logout();
            return false;
        }

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        servletRequest.setAttribute("admin", admin);

        if (admin.getType().equals(Admin.SUPER_ADMIN)) {
            return true;
        }

        // 权限验证
        subject.checkPermission(request.getRequestURI());

        return true;
    }

}
